package com.clp.util.hutool.core.text;

import com.clp.util.hutool.core.convert.Convert;
import com.clp.util.hutool.core.util.ArrayUtil;
import com.clp.util.hutool.core.util.StrUtil;

import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;

/**
 * 可复用的字符串生成器，非线程安全
 */
public class StrBuilder implements CharSequence, Appendable, Serializable {
    /**
     * 默认容量
     */
    private static final int DEFAULT_CAPACITY = 16;
    /**
     * 存放的字符数组
     */
    private char[] value;
    /**
     * 当前指针位置，或者叫做已经加入的字符数，此位置总在最后一个字符之后
     */
    private int position;

    /**
     * 创建字符串构建器
     */
    public static StrBuilder create() {
        return new StrBuilder();
    }

    public static StrBuilder create(int initialCapacity) {
        return new StrBuilder(initialCapacity);
    }

    /**
     * 创建字符串构建器
     * @param strs 初始字符串
     * @return
     */
    public static StrBuilder create(CharSequence... strs) {
        return new StrBuilder(strs);
    }

    public StrBuilder() {
        this(DEFAULT_CAPACITY);
    }

    public StrBuilder(int initialCapacity) {
        value = new char[initialCapacity];
    }

    public StrBuilder(CharSequence... strs) {
        this(ArrayUtil.isEmpty(strs) ? DEFAULT_CAPACITY : (totalLength(strs) + DEFAULT_CAPACITY));
        for (CharSequence str : strs) {
            append(str);
        }
    }

    /**
     * 给定字符串数组的总长度<br>
     * null字符长度定义为0
     *
     * @param strs 字符串数组
     * @return 总长度
     * @since 4.0.1
     */
    private static int totalLength(CharSequence... strs) {
        int totalLength = 0;
        for (CharSequence str : strs) {
            totalLength += (null == str ? 4 : str.length());
        }
        return totalLength;
    }

    public StrBuilder append(Object obj) {
        return insert(this.position, obj);
    }

    @Override
    public StrBuilder append(char c) {
        return insert(this.position, c);
    }

    public StrBuilder append(char[] src) {
        if (ArrayUtil.isEmpty(src)) {
            return this;
        }
        return append(src, 0, src.length);
    }

    public StrBuilder append(char[] src, int srcPos, int length) {
        return insert(this.position, src, srcPos, length);
    }

    @Override
    public StrBuilder append(CharSequence csq) {
        return insert(this.position, csq);
    }

    @Override
    public StrBuilder append(CharSequence csq, int start, int end) {
        return insert(this.position, csq, start, end);
    }

    public StrBuilder insert(int index, char c) {
        moveDataAfterIndex(index, 1);
        value[index] = c;
        this.position = Math.max(this.position, index) + 1;
        return this;
    }

    /**
     * 指定位置插入数据<br>
     * 如果插入位置为当前位置，则定义为追加<br>
     * 如果插入位置大于当前位置，则中间部分补充空格
     *
     * @param index  插入位置
     * @param src    源数组
     * @param srcPos 位置
     * @param length 长度
     * @return this
     */
    public StrBuilder insert(int index, char[] src, int srcPos, int length) {
        if (ArrayUtil.isEmpty(src) || srcPos > src.length || length <= 0) {
            return this;
        }
        if (index < 0) {
            index = 0;
        }
        if (srcPos < 0) {
            srcPos = 0;
        } else if (srcPos + length > src.length) {
            // 长度越界，只截取最大长度
            length = src.length - srcPos;
        }

        moveDataAfterIndex(index, length);
        // 插入数据
        System.arraycopy(src, srcPos, value, index, length);
        this.position = Math.max(this.position, index) + length;
        return this;
    }

    /**
     * 指定位置插入字符串的某个部分<br>
     * 如果插入位置为当前位置，则定义为追加<br>
     * 如果插入位置大于当前位置，则中间部分补充空格
     *
     * @param index 位置
     * @param csq   字符串
     * @param start 字符串开始位置（包括）
     * @param end   字符串结束位置（不包括）
     * @return this
     */
    public StrBuilder insert(int index, CharSequence csq, int start, int end) {
        if (csq == null) {
            csq = "null";
        }
        final int csqLen = csq.length();
        if (start > csqLen) {
            return this;
        }
        if (start < 0) {
            start = 0;
        }
        if (end > csqLen) {
            end = csqLen;
        }
        if (start >= end) {
            return this;
        }
        if (index < 0) {
            index = 0;
        }

        final int length = end - start;
        moveDataAfterIndex(index, length);
        for (int i = start, j = this.position; i < end; i++, j++) {
            value[j] = csq.charAt(i);
        }
        this.position = Math.max(this.position, index) + length;
        return this;
    }

    private void moveDataAfterIndex(int index, int length) {
        ensureCapacity(Math.max(this.position, index) + length);
        if (index < this.position) {
            // 插入位置在已有数据范围内，后移插入位置之后的数据
            System.arraycopy(this.value, index, this.value, index + length, this.position - index);
        } else if (index > this.position) {
            // 插入位置超出范围，则当前位置到index清除为空格
            Arrays.fill(this.value, this.position, index, StrUtil.C_SPACE);
        }
        // 不位移
    }

    private void ensureCapacity(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0) {
            expandCapacity(minimumCapacity);
        }
    }

    private void expandCapacity(int minimumCapacity) {
        int newCapacity = (value.length << 1) + 2;
        // overflow-conscious code
        if (newCapacity - minimumCapacity < 0) {
            newCapacity = minimumCapacity;
        }
        if (newCapacity < 0) {
            throw new OutOfMemoryError("Capacity is too long and max than Integer.MAX");
        }
        value = Arrays.copyOf(value, newCapacity);
    }

    public StrBuilder insert(int index, CharSequence csq) {
        if (null == csq) {
            csq = StrUtil.EMPTY;
        }
        int len = csq.length();
        moveDataAfterIndex(index, csq.length());
        if (csq instanceof String) {
            ((String) csq).getChars(0, len, this.value, index);
        } else if (csq instanceof StringBuilder) {
            ((StringBuilder) csq).getChars(0, len, this.value, index);
        } else if (csq instanceof StringBuffer) {
            ((StringBuffer) csq).getChars(0, len, this.value, index);
        } else if (csq instanceof StrBuilder) {
            ((StrBuilder) csq).getChars(0, len, this.value, index);
        } else {
            for (int i = 0, j = this.position; i < len; i++, j++) {
                this.value[j] = csq.charAt(i);
            }
        }
        this.position = Math.max(this.position, index) + len;
        return this;
    }

    public StrBuilder getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) {
        if (srcBegin < 0) {
            srcBegin = 0;
        }
        if (srcEnd < 0) {
            srcEnd = 0;
        } else if (srcEnd > this.position) {
            srcEnd = this.position;
        }
        if (srcBegin > srcEnd) {
            throw new StringIndexOutOfBoundsException("srcBegin > srcEnd");
        }
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
        return this;
    }

    /**
     * 追加对象，对象会被转换为字符串
     * @param index
     * @param obj
     * @return
     */
    public StrBuilder insert(int index, Object obj) {
        if (obj instanceof CharSequence) {
            return insert(index, (CharSequence) obj);
        }
        return insert(index, Convert.toStr(obj));
    }

    @Override
    public int length() {
        return 0;
    }

    @Override
    public char charAt(int index) {
        return 0;
    }

    @Override
    public CharSequence subSequence(int start, int end) {
        return null;
    }
}
